import { useState, useEffect } from 'react'
import { Row, Col, Button, Select, Space, Empty, Timeline, Card } from 'antd'
import { Link, useSearchParams } from 'react-router-dom'
import { useSelector } from 'react-redux'
import { useAppDispatch, RootState } from '@/store'
import { getTimeAction, setInfos } from '@/store/modules/signs'
import { getApplyAction, setApplyList } from '@/store/modules/checks'
import { toZero } from '@/utils/common'
import { isEmpty } from 'lodash-es'
import styles from './index.module.scss'

const date = new Date()
const year = date.getFullYear()

const Exception = () => {
  const [searchParams, setSearchParams] = useSearchParams()
  const [month, setMonth] = useState(
    searchParams.get('month')
      ? Number(searchParams.get('month')) - 1
      : date.getMonth()
  )
  const singsInfos = useSelector((state: RootState) => state.signs.infos)
  const usersInfos = useSelector((state: RootState) => state.users.infos)
  const applyList = useSelector((state: RootState) => state.checks.applyList)
  const dispatch = useAppDispatch()

  useEffect(() => {
    if (isEmpty(singsInfos)) {
      dispatch(getTimeAction({ userid: usersInfos._id })).then((action) => {
        const { payload } = action
        const { errcode, infos } = payload
        if (errcode === 0) {
          dispatch(setInfos(infos))
        }
      })
    }
  }, [singsInfos, dispatch, usersInfos])

  useEffect(() => {
    if (isEmpty(applyList)) {
      dispatch(getApplyAction({ applicantid: usersInfos._id })).then(
        (action) => {
          const { payload } = action
          const { errcode, rets } = payload
          if (errcode === 0) {
            dispatch(setApplyList(rets))
          }
        }
      )
    }
  }, [applyList, dispatch, usersInfos])

  let details
  if (singsInfos.detail) {
    const detailMonth = singsInfos.detail[toZero(month + 1)]
    details = Object.entries(detailMonth)
      .filter((v) => v[1] !== '正常出勤')
      .sort()
  }

  const applyListMonth = applyList.filter(({ time }) => {
    const startTime = time[0].split(' ')[0].split('-')
    const endTime = time[1].split(' ')[0].split('-')
    return startTime[1] <= toZero(month + 1) && endTime[1] >= toZero(month + 1)
  })

  const handleChange = (value: number) => {
    setMonth(value)
    setSearchParams({ month: String(value + 1) })
  }
  const renderTime = (date: string) => {
    const res = singsInfos.time[toZero(month + 1)][date]
    if (Array.isArray(res)) {
      return res.join('-')
    } else {
      return '暂无打卡记录'
    }
  }

  const monthOptions = []
  for (let i = 0; i < 12; i++) {
    monthOptions.push(
      <Select.Option key={i} value={i}>
        {i + 1}月
      </Select.Option>
    )
  }

  return (
    <div className={styles.exception}>
      <Row justify="space-between" align="middle">
        <Link to="/apply">
          <Button type="primary">异常处理</Button>
        </Link>
        <Space>
          <Button>{year}年</Button>
          <Select value={month} onChange={handleChange}>
            {monthOptions}
          </Select>
        </Space>
      </Row>
      <Row className={styles['exception-line']} gutter={20}>
        <Col span={12}>
          {details ? (
            <Timeline
              items={details.map((item) => {
                return {
                  children: (
                    <>
                      <h3>
                        {year}/{month + 1}/{item[0]}
                      </h3>
                      <Card className={styles['exception-card']}>
                        <Space>
                          <h4>{item[1]}</h4>
                          <p>考勤详情：{renderTime(item[0])}</p>
                        </Space>
                      </Card>
                    </>
                  ),
                }
              })}
            />
          ) : (
            <Empty description="暂无异常考勤" imageStyle={{ height: 200 }} />
          )}
        </Col>
        <Col span={12}>
          {applyListMonth.length ? (
            <Timeline
              items={applyListMonth.map((item) => {
                return {
                  children: (
                    <>
                      <h3>{item.reason as string}</h3>
                      <Card className={styles['exception-card']}>
                        <h4>{item.state as string}</h4>
                        <p className={styles['exception-content']}>
                          申请日期 {(item.time as string[])[0]} -{' '}
                          {(item.time as string[])[1]}
                        </p>
                        <p className={styles['exception-content']}>
                          申请详情 {item.note as string}
                        </p>
                      </Card>
                    </>
                  ),
                }
              })}
            />
          ) : (
            <Empty description="暂无申请审批" imageStyle={{ height: 200 }} />
          )}
        </Col>
      </Row>
    </div>
  )
}

export default Exception
